﻿@{
    ViewBag.Title = "Giao việc";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/extjs/ux/boxselect/BoxSelect.js"></script>
<link href="~/extjs/ux/boxselect/BoxSelect.css" rel="stylesheet" />
<link href="~/Content/TaskDetail.css" rel="stylesheet" />
<script type="text/javascript">

    var required = '<span style="color:red;font-weight:bold" data-qtip="Bắt buộc nhập">*</span>';
    
    Ext.Loader.setPath('Ext.ux', '/extjs/ux');
    //Ext.Loader.setPath('Ext.ux.superbox', '/extjs/ux/superbox');
    //Ext.Loader.setPath('Ext.ux.boxselect', '/extjs/ux/boxselect');

    Ext.require([
        'Ext.data.*',
        'Ext.grid.*',
        'Ext.ux.DataTip'
        //'Ext.ux.boxselect.BoxSelect'
    ]);

    Ext.define('VTV.TaDMS.Extjs.Model.Task', {
        extend: 'Ext.data.Model',
        fields: [{
            name: 'TaskId', mapping: 'TaskId', type: 'int'
        }, {
            name: 'CreateBy', mapping: 'CreateBy', type: 'int'
        }, {
            name: 'TaskName', mapping: 'TaskName', type: 'string'
        }, {
            name: 'TaskType', mapping: 'TaskType', type: 'string'
        }, {
            name: 'StartDate', mapping: 'StartDate', type: 'date'
        }, {
            name: 'EndDate', mapping: 'EndDate', type: 'date'
        }, {
            name: 'ActualEndDate', mapping: 'ActualEndDate', type: 'date'
        }, {
            name: 'Status', mapping: 'Status', type: 'string'
        }, {
            name: 'Descriptions', mapping: 'Descriptions', type: 'string'
        }, {
            name: 'CreateDate', mapping: 'CreateDate', type: 'date'
        }],
        idProperty: 'TaskId'
    });

    Ext.define('VTV.TaDMS.Extjs.Model.Employee', {
        extend: 'Ext.data.Model',
        fields: [{
            name: 'EmployeeId', mapping: 'EmployeeId', type: 'int'
        }, {
            name: 'DepartmentId', mapping: 'DepartmentId', type: 'int'
        }, {
            name: 'FirstName', mapping: 'FirstName', type: 'string'
        }, {
            name: 'LastName', mapping: 'LastName', type: 'string'
        }, {
            name: 'BirthDate', mapping: 'BirthDate', type: 'date'
        }, {
            name: 'Address', mapping: 'Address', type: 'string'
        }, {
            name: 'MobilePhone', mapping: 'MobilePhone', type: 'string'
        }, {
            name: 'Email', mapping: 'Email', type: 'string'
        }, {
            name: 'Note', mapping: 'Note', type: 'string'
        }],
        idProperty: 'EmployeeId'
    });

    Ext.define('VTV.TaDMS.Extjs.Model.Combo', {
        extend: 'Ext.data.Model',
        fields: [{
            name: 'EmployeeId', mapping: 'EmployeeId', type: 'int'
        }, {
            name: 'FirstName', mapping: 'FirstName', type: 'string'
        }, {
            name: 'LastName', mapping: 'LastName', type: 'string'
        }, {
            name: 'Display',
            convert: function (v, rec) {
                var firstName = rec.get('FirstName');
                var lastName = rec.get('LastName');

                return firstName + ' ' + lastName;
            }
        }]
    });

    Ext.onReady(function () {
        Ext.QuickTips.init();

        var taskStore = Ext.create('Ext.data.Store', {
            model: 'VTV.TaDMS.Extjs.Model.Task',
            autoLoad: { param: { start: 0, limit: 15 } },
            pageSize: 10,
            proxy: {
                type: 'ajax',
                api: {
                    create: '/api/ApiTask/Create',
                    read: '/api/ApiTask/AssignTask',
                    update: '/api/ApiTask/Update',
                    destroy: '/api/ApiTask/Delete'
                },
                reader: {
                    root: 'data',
                    type: 'json',
                    successProperty: 'success',
                    messageProperty: 'message',
                    totalProperty: 'total'
                },
                writer: {
                    type: 'json',
                    writeAllFields: false
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        Ext.MessageBox.show({
                            title: 'Lỗi',
                            msg: operation.getError(),
                            icon: Ext.MessageBox.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
            }
        });

        var rowEditing = Ext.create('Ext.grid.plugin.RowEditing', {
            listeners: {
                cancelEdit: function (editor, context) {
                    if (context.record.phantom) {
                        store.remove(context.record);
                    }
                },
                edit: function (editor, context, eOpts) {
                    var result = '';
                    for (var i = 0; i < context.grid.columns.length; i++) {
                        if (context.record.isModified(context.grid.columns[i].dataIndex)) {
                            result = result + '$' + context.grid.columns[i].dataIndex;
                        }
                    }

                    if (result.length > 0) {

                        var entity = {
                            TaskId: context.record.get('TaskId'),
                            TaskName: context.record.get('TaskName'),
                            TaskType: context.record.get('TaskType').trim() != "" ? context.record.get('TaskType').trim() : null,
                            StartDate: context.record.get('StartDate') != "" ? context.record.get('StartDate') : null,
                            EndDate: context.record.get('EndDate') != "" ? context.record.get('EndDate') : null
                        };

                        Ext.Ajax.request({
                            url: '/api/ApiTask/Update',
                            method: 'POST',
                            jsonData: entity,
                            params: {
                                fields: result.substring(1)
                            },
                            success: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                if (responseData.success == true) {
                                    context.record.commit();
                                } else {
                                    Ext.MessageBox.show({
                                        title: 'Lỗi',
                                        msg: responseData.message,
                                        icon: Ext.MessageBox.ERROR,
                                        buttons: Ext.Msg.OK
                                    });
                                }
                            },
                            failure: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                alert("Lỗi. " + responseData.message);
                            }
                        });

                    }
                }
            }
        });

        var taskGrid = Ext.create('Ext.grid.Panel', {
            title: 'Danh sách công việc',
            region: 'center',
            store: taskStore,
            plugins: [rowEditing],
            columns: [{
                text: 'Tên công việc', flex: 1, dataIndex: 'TaskName', field: { xtype: 'textfield' }
            }, {
                text: 'Loại', width: 170, dataIndex: 'TaskType', field: { xtype: 'textfield' }
            }, {
                text: 'Ngày bắt đầu', width: 150, dataIndex: 'StartDate', renderer: Ext.util.Format.dateRenderer('d-m-Y'), field: { xtype: 'datefield' }
            }, {
                text: 'Ngày kết thúc', width: 150, dataIndex: 'EndDate', renderer: Ext.util.Format.dateRenderer('d-m-Y'), field: { xtype: 'datefield' }
            }, {
            //    text: 'Trạng thái', width: 70, dataIndex: 'Status', field: { xtype: 'textfield' }
            //}, {
            //    text: 'Mô tả', flex: 1, dataIndex: 'Descriptions', field: { xtype: 'textfield' }
            //}, {
                text: 'Người tạo', width: 150, dataIndex: 'CreateBy'
            }, {
                menuDisabled: true,
                sortable: false,
                xtype: 'actioncolumn',
                text: 'Thao tác',
                align: 'center',
                width: 70,
                items: [{
                    icon: '../Content/icon/delete.gif', tooltip: 'Xóa',
                    handler: function (grid, rowIndex, colIndex, item, e, record) {

                        Ext.Msg.show({
                            title: 'Xác nhận', msg: 'Xác nhận xóa dữ liệu ?', width: 250, buttons: Ext.MessageBox.OKCANCEL, icon: Ext.MessageBox.QUESTION,
                            buttonText: {
                                ok: 'Xóa', cancel: 'Hủy'
                            },
                            fn: function (buttonId, text, opt) {
                                if (buttonId == 'ok') {
                                    var gridStore = grid.getStore();
                                    var rec = gridStore.getAt(rowIndex);
                                    if (rec) {
                                        var entity = {
                                            TaskId: rec.get('TaskId')
                                        };

                                        Ext.Ajax.request({
                                            url: '/api/ApiTask/Delete',
                                            method: 'POST',
                                            jsonData: entity,
                                            success: function (transport, option) {
                                                var responseData = Ext.decode(transport.responseText);
                                                if (responseData.success == true) {
                                                    gridStore.remove(rec);

                                                } else {
                                                    Ext.MessageBox.show({
                                                        title: 'Lỗi',
                                                        msg: responseData.message,
                                                        icon: Ext.MessageBox.ERROR,
                                                        buttons: Ext.Msg.OK
                                                    });
                                                }
                                            },
                                            failure: function (transport, option) {
                                                var responseData = Ext.decode(transport.responseText);
                                                Ext.MessageBox.show({
                                                    title: 'Lỗi',
                                                    msg: responseData.message,
                                                    icon: Ext.MessageBox.ERROR,
                                                    buttons: Ext.Msg.OK
                                                });
                                            }
                                        });
                                    }
                                }
                                else if (buttonId == 'cancel') {

                                }
                            }
                        });
                    }
                }, {
                    icon: '../Content/icon/edit.png', tooltip: 'Sửa',
                    handler: function (grid, rowIndex, colIndex, item, e, record) {
                        var row = record;
                        if (row) {
                            Ext.create('TaskWindow', {
                                id: 'newTaskWindow',
                                rec: row
                            }).show();
                        }
                    }
                }]
            }],
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    text: 'Giao việc mới',
                    iconCls: 'icon-add',
                    handler: function () {
                        Ext.create('TaskWindow', {
                            id: 'newTaskWindow'
                        }).show();
                    }
                }]
            }],
            bbar: new Ext.PagingToolbar({
                pageSize: 10,
                store: taskStore,
                displayInfo: true,
                displayMsg: 'Danh sách: từ {0} đến {1}.  Tổng số: {2}',
                emptyMsg: "Không có bản ghi nào"
            }),
            listeners: {
                select: function (record, index, eOpts) {
                    var data = {
                        TaskName: record.lastSelected.get('TaskName'),
                        CreateBy: record.lastSelected.get('CreateBy'),
                        CreateDate: record.lastSelected.get('CreateDate'),
                        StartDate: record.lastSelected.get('StartDate'),
                        EndDate: record.lastSelected.get('EndDate'),
                        Descriptions: record.lastSelected.get('Descriptions')
                    };
                    
                    var taskId = record.lastSelected.get('TaskId');
                    if (taskId) {
                        resourceTaskStore.getProxy().extraParams = {
                            taskId: taskId
                        };
                        resourceTaskStore.load();
                        resourceTaskStore.on('load', function (records, operation, success) {
                            if (success) {
                                var employees = new Array();
                                for (var i = 0; i < operation.length; i++) {
                                    var emp = {
                                        FirstName: operation[i].get('FirstName'),
                                        LastName: operation[i].get('LastName')
                                    };
                                    employees[i] = emp;
                                }

                                data['Employees'] = employees;
                            } else {
                                var error = {
                                    FirstName: 'XẢY RA LỖI',
                                    LastName: ''
                                };
                                
                                data['Employees'] = error;
                            }

                            taskTpl.overwrite(taskDetail.body, data);
                        });
                    }
                }
            }

        });

        var taskDetail = Ext.create('Ext.panel.Panel', {
            autoScroll: true, border: false, region: 'south', split: true, collapsible: true, id: 'taskDetail', height: 350
        });

        var taskTpl = new Ext.XTemplate(
            '<div id="taskDetail-wrapper">',
                '<div class="taskDetail-title">',
                    '<div class="taskDetail-title-right">{TaskName}</div>',
                '</div>',
                '<div class="taskDetail-item">',
                    '<div class="taskDetail-item-left">Người tạo:</div>',
                    '<div class="taskDetail-item-right">{CreateBy} - {CreateDate:date("d/m/Y H:i:s")}</div>',
                '</div>',
                '<div class="taskDetail-item">',
                    '<div class="taskDetail-item-left">Ngày bắt đầu:</div>',
                    '<div class="taskDetail-item-right">{StartDate:date("d/m/Y")}</div>',
                '</div>',
                '<div class="taskDetail-item">',
                    '<div class="taskDetail-item-left">Ngày kết thúc:</div>',
                    '<div class="taskDetail-item-right">{EndDate:date("d/m/Y")}</div>',
                '</div>',
                '<div class="taskDetail-item">',
                    '<div class="taskDetail-item-left">Thực hiện:</div>',
                    '<div class="taskDetail-item-right">',
                        '<ol style="padding: 0px; margin: 0; padding-left: 20px;">',
                            '<tpl for="Employees">',
                                '<li>{FirstName} {LastName}</li>',
                            '</tpl>',
                        '</ol>',
                    '</div>',
                '</div>',
                '<div class="taskDetail-item">',
                    '<div class="taskDetail-item-left">Mô tả:</div>',
                    '<div class="taskDetail-item-right">{Descriptions}</div>',
                '</div>',
            '</div>'
        );

        var resourceTaskStore = Ext.create('Ext.data.Store', {
            model: 'VTV.TaDMS.Extjs.Model.Employee',
            pageSize: 100,
            proxy: {
                type: 'ajax',
                api: {
                    create: '',
                    read: '/api/ApiTaskEmployee/ResourceOfTask',
                    destroy: '/api/ApiEmployee/Delete'
                },
                reader: {
                    root: 'data', type: 'json', successProperty: 'success', messageProperty: 'message', totalProperty: 'total'
                },
                writer: {
                    type: 'json', writeAllFields: false
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        Ext.MessageBox.show({
                            title: 'Lỗi', msg: operation.getError(), icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                        });
                    }
                }
            }
        });

        var comboStore = Ext.create('Ext.data.Store', {
            model: 'VTV.TaDMS.Extjs.Model.Combo',
            pageSize: 10,
            proxy: {
                type: 'ajax',
                api: {
                    read: '/api/ApiTask/GetComboData'
                },
                reader: {
                    root: 'data',
                    type: 'json',
                    successProperty: 'success',
                    totalProperty: 'total'
                },
                listeners: {
                    exception: function (proxy, response, operation) {
                        Ext.MessageBox.show({
                            title: 'Lỗi',
                            msg: operation.getError(),
                            icon: Ext.MessageBox.ERROR,
                            buttons: Ext.Msg.OK
                        });
                    }
                }
            },
            listeners: {
                beforeload: function (store, operation, eOpts) {
                    var proxy = store.getProxy();
                    if (proxy) {
                        var isAll = Ext.getCmp('chkIsAll').getValue() ? 0 : 1;
                        proxy.extraParams = {
                            all: isAll
                        };
                    } else {
                        return;
                    }
                }
            }
        });

        var resourceTaskGrid = Ext.create('Ext.grid.Panel', {
            title: 'Danh sách nhân viên',
            region: 'south',
            height: 300,
            store: resourceTaskStore,
            collapsible: true,
            split: true,
            emptyText: 'Không có nhân viên nào',
            columns: [{
                text: 'Họ', width: 130, dataIndex: 'FirstName', field: { xtype: 'textfield' }
            }, {
                text: 'Tên', width: 100, dataIndex: 'LastName', field: { xtype: 'textfield' }
            }, {
                text: 'Ngày sinh', width: 140, dataIndex: 'BirthDate', renderer: Ext.util.Format.dateRenderer('d-m-Y'), field: { xtype: 'datefield' }
            }, {
                text: 'Điện thoại', width: 150, dataIndex: 'MobilePhone', field: { xtype: 'textfield' }
            }, {
                text: 'Email', flex: 1, dataIndex: 'Email', field: { xtype: 'textfield' }
            }, {
                menuDisabled: true,
                sortable: false,
                xtype: 'actioncolumn',
                text: 'Thao tác',
                align: 'center',
                width: 60,
                items: [{
                    icon: '../Content/icon/delete.gif',
                    tooltip: 'Xóa',
                    handler: function (grid, rowIndex, colIndex, item, e, record) {
                        var task = taskGrid.getSelectionModel() ? taskGrid.getSelectionModel().getSelection() : null;
                        if (task[0]) {
                            Ext.Msg.show({
                                title: 'Xác nhận',
                                msg: 'Xác nhận xóa dữ liệu ?',
                                width: 250,
                                buttons: Ext.MessageBox.OKCANCEL,
                                buttonText: {
                                    ok: 'Xóa',
                                    cancel: 'Hủy'
                                },
                                icon: Ext.MessageBox.QUESTION,
                                fn: function (buttonId, text, opt) {
                                    if (buttonId == 'ok') {
                                        var gridStore = grid.getStore();
                                        var rec = gridStore.getAt(rowIndex);
                                        if (rec) {
                                            var entity = {
                                                EmployeeId: rec.get('EmployeeId'),
                                                TaskId: task[0].get('TaskId')
                                            };

                                            Ext.Ajax.request({
                                                url: '/api/ApiTaskEmployee/Delete',
                                                method: 'POST',
                                                jsonData: entity,
                                                success: function (transport, option) {
                                                    var responseData = Ext.decode(transport.responseText);
                                                    if (responseData.success == true) {
                                                        gridStore.remove(rec);

                                                    } else {
                                                        Ext.MessageBox.show({
                                                            title: 'Lỗi',
                                                            msg: responseData.message,
                                                            icon: Ext.MessageBox.ERROR,
                                                            buttons: Ext.Msg.OK
                                                        });
                                                    }
                                                },
                                                failure: function (transport, option) {
                                                    var responseData = Ext.decode(transport.responseText);
                                                    Ext.MessageBox.show({
                                                        title: 'Lỗi',
                                                        msg: responseData.message,
                                                        icon: Ext.MessageBox.ERROR,
                                                        buttons: Ext.Msg.OK
                                                    });
                                                }
                                            });
                                        }
                                    }
                                    else if (buttonId == 'cancel') {

                                    }
                                }
                            });
                        }

                    }
                }, {
                    icon: '../Content/icon/edit.gif',
                    tooltip: 'Sửa',
                    handler: function (grid, rowIndex, colIndex, item, e, record) {
                        var row = grid.getStore().getAt(rowIndex);
                        if (row) {
                            Ext.create('TaskWindow', {
                                id: 'newTaskWindow',
                                rec: row
                            }).show();
                        }
                    }
                }]
            }],
            dockedItems: [{
                xtype: 'toolbar',
                items: [{
                    text: 'Chọn nhân viên',
                    iconCls: 'icon-add',
                    handler: function () {
                        var task = taskGrid.getSelectionModel() ? taskGrid.getSelectionModel().getSelection() : null;
                        if (task[0]) {
                            var combo = Ext.getCmp('comboboxD1');
                            if (combo) {
                                var employee = combo.getValue();
                                if (employee) {

                                    var entity = {
                                        EmployeeId: employee,
                                        TaskId: task[0].get('TaskId')
                                    };

                                    Ext.Ajax.request({
                                        url: '/api/ApiTaskEmployee/Create',
                                        method: 'POST',
                                        jsonData: entity,
                                        success: function (transport, option) {
                                            var responseData = Ext.decode(transport.responseText);
                                            if (responseData.success == true) {

                                                resourceTaskGrid.getStore().insert(0, responseData.data);

                                            } else {
                                                Ext.MessageBox.show({
                                                    title: 'Lỗi',
                                                    msg: responseData.message,
                                                    icon: Ext.MessageBox.ERROR,
                                                    buttons: Ext.Msg.OK
                                                });
                                            }
                                        },
                                        failure: function (transport, option) {
                                            var responseData = Ext.decode(transport.responseText);
                                            alert("Lỗi. " + responseData.message);
                                        }
                                    });
                                }
                            }
                        }
                    }
                }, {
                    xtype: 'combo',
                    id: 'comboboxD1',
                    store: comboStore,
                    valueField: 'EmployeeId',
                    displayField: 'Display',
                    typeAhead: true,
                    typeAheadDelay: 300,
                    tooltip: 'Chọn nhân viên',
                    selectOnFocus: true,
                    triggerAction: 'all',
                    width: 250,
                    listConfig: {
                        loadingText: 'Tìm kiếm',
                        emptyText: 'Không có kết quả phù hợp',
                        getInnerTpl: function () {
                            return '<div style="padding: 5px 5px 5px 10px; border-bottom: dotted 1px beige;">' +
                                '{FirstName}' + ' {LastName}' +
                                '</div>';
                        }
                    },
                    pageSize: 10,
                    minChars: 2
                }, {
                    //xtype: 'checkbox', boxLabel: 'Danh sách mở rộng',
                    //checked: false,
                    //id: 'chkIsAll'
                }]
            }]
        });

        Ext.create('Ext.container.Viewport', {
            layout: { type: 'border' },
            items: [taskGrid, taskDetail]
        });

        Ext.define('TaskWindow', {
            extend: 'Ext.window.Window',
            title: 'Giao việc mới', modal: true, closeable: true, width: 600, layout: 'fit',
            header: {
                titleAlign: 'center'
            },
            resizable: {
                handles: 'e w'
            },
            items: {
                xtype: 'form', layout: 'form', autoHeight: true, bodyPadding: '10 10 5 10',
                fieldDefaults: {
                    msgTarget: 'side', labelWidth: 100, magrins: '0 0 5 0'
                },
                plugins: {
                    ptype: 'datatip'
                },
                defaultType: 'textfield',
                items: [{
                    fieldLabel: 'Tên công việc', id: 'txtTaskName', tooltip: 'Nhập tên công việc', anchor:'100%'
                }, {
                    fieldLabel: 'Thực hiện', tooltip: 'Chọn nhân viên', xtype: 'boxselect', id: 'comboboxD2', store: comboStore, valueField: 'EmployeeId',
                    displayField: 'Display', queryMode: 'remote', delimiter: '$', pageSize: 10, width: 250, minChars: 1, stacked: true, pinList: true,
                    listConfig: {
                        loadingText: 'Tìm kiếm', emptyText: 'Không có kết quả phù hợp',
                        getInnerTpl: function () {
                            return '<div style="padding: 5px 5px 5px 10px; border-bottom: dotted 1px beige;">' +
                                '{FirstName}' + ' {LastName}' +
                                '</div>';
                        }
                    }
                }, {
                    fieldLabel: ' ',  tooltip: 'Danh sách mở rộng', xtype: 'checkbox', checked: false, id: 'chkIsAll', boxLabel: 'Hiển thị đầy đủ danh sách nhân viên'
                }, {
                    xtype: 'fieldcontainer', fieldLabel: 'Loại công việc', defaultType: 'radiofield', tooltip: 'Chọn loại công việc',
                    defaults: {
                        flex: 1
                    },
                    layout: {
                        type: 'hbox', pack: 'start', align: 'stretch'
                    },
                    items: [{
                        boxLabel: 'Ngắn hạn', name: 'TaskType', id: 'radio1', checked: true
                    }, {
                        boxLabel: 'Dài hạn', name: 'TaskType', id: 'radio2'
                    }]
                }, {
                    xtype: 'datefield', fieldLabel: 'Ngày bắt đầu', id: 'txtStartDate', format: 'd-m-Y', allowBlank: false, tooltip: 'Chọn ngày bắt đầu'
                }, {
                    xtype: 'datefield', fieldLabel: 'Ngày kết thúc', id: 'txtEndDate', format: 'd-m-Y', tooltip: 'Chọn ngày kết thúc'
                }, {
                    xtype: 'htmleditor', id: 'txtDescript', fieldLabel: 'Mô tả công việc', height: 250, labelAlign: 'top', anchor: '100%'
                }]
            },
            buttons: [{
                text: 'Lưu',
                id: 'btnSave',
                handler: function () {

                    var row = Ext.getCmp('newTaskWindow').rec;
                    if (row) {
                        var fieldsChange = '';
                        var taskName = Ext.getCmp('txtTaskName').getValue(),
                            taskType = Ext.getCmp('radio1').getValue() ? 'S' : 'L',
                            startDate = Ext.getCmp('txtStartDate').getValue(),
                            endDate = Ext.getCmp('txtEndDate').getValue(),
                            descriptions = Ext.getCmp('txtDescript').getValue();

                        if (row.raw.TaskName != taskName) {
                            fieldsChange += '$TaskName';
                        }
                        if (row.raw.TaskType != taskType) {
                            fieldsChange += '$TaskType';
                        }
                        if (row.raw.StartDate != startDate) {
                            fieldsChange += '$StartDate';
                        }
                        if (row.raw.EndDate != endDate) {
                            fieldsChange += '$EndDate';
                        }
                        if (row.raw.Descriptions != descriptions) {
                            fieldsChange += '$Descriptions';
                        }

                        if (fieldsChange.length > 0) {
                            var entityUpdate = {
                                TaskId: row.get('TaskId'),
                                TaskName: taskName,
                                TaskType: taskType,
                                StartDate: startDate,
                                EndDate: endDate,
                                Descriptions: descriptions
                            };
                            
                            Ext.Ajax.request({
                                url: '/api/ApiTask/Update',
                                method: 'POST',
                                jsonData: entityUpdate,
                                params: {
                                    fields: fieldsChange.substring(1)
                                },
                                success: function (transport, option) {
                                    var responseData = Ext.decode(transport.responseText);
                                    if (responseData.success == true) {
                                        var changed = taskGrid.getStore().findRecord('TaskId', row.get('TaskId'));
                                        if (changed) {
                                            var arr = fieldsChange.substring(1).split('$');
                                            changed.beginEdit();
                                            for (var i = 0; i < arr.length; i++) {
                                                changed.set(arr[i], Object.getOwnPropertyDescriptor(entityUpdate, arr[i]).value);
                                            }
                                            changed.endEdit();
                                            changed.commit();
                                        }
                                        
                                    } else {
                                        Ext.MessageBox.show({
                                            title: 'Lỗi trong khi sửa công việc', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                        });
                                    }
                                },
                                failure: function (transport, option) {
                                    var responseData = Ext.decode(transport.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Lỗi trong khi sửa công việc', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                    });
                                }
                            });
                        }
                        
                        var oldSource = [];
                        for (var i = 0; i < row.raw.TaskEmployees.length; i++) {
                            oldSource.push(row.raw.TaskEmployees[i].EmployeeId);
                        }

                        var newSource = Ext.getCmp('comboboxD2').getValue();

                        if (oldSource.length != newSource.length) {

                            var newEntity = [];
                            for (var i = 0; i < newSource.length; i++) {
                                var employeeEntity = {
                                    EmployeeId: newSource[i]
                                };

                                newEntity.push(employeeEntity);
                            }

                            Ext.Ajax.request({
                                url: '/api/ApiTaskEmployee/UpdateList',
                                method: 'POST',
                                jsonData: newEntity,
                                params: {
                                    taskId: row.raw.TaskId
                                },
                                success: function (transport, option) {
                                    var responseData = Ext.decode(transport.responseText);
                                    if (responseData.success == true) {


                                    } else {
                                        Ext.MessageBox.show({
                                            title: 'Lỗi trong khi thêm nhân viên', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                        });
                                    }
                                },
                                failure: function (transport, option) {
                                    var responseData = Ext.decode(transport.responseText);
                                    Ext.MessageBox.show({
                                        title: 'Lỗi trong khi thêm nhân viên', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                    });
                                }
                            });
                        } else {
                            var oldSourceTemp = oldSource.sort();
                            var newSourceTemp = newSource.sort();
                            for (var i = 0; i < newSourceTemp.length; i++) {
                                if (oldSourceTemp[i] != newSourceTemp[i]) {

                                    var newEntity2 = [];
                                    for (var i = 0; i < newSource.length; i++) {
                                        var employeeEntity2 = {
                                            EmployeeId: newSource[i]
                                        };

                                        newEntity2.push(employeeEntity2);
                                    }

                                    Ext.Ajax.request({
                                        url: '/api/ApiTaskEmployee/UpdateList',
                                        method: 'POST',
                                        jsonData: newEntity2,
                                        params: {
                                            taskId: row.raw.TaskId
                                        },
                                        success: function (transport, option) {
                                            var responseData = Ext.decode(transport.responseText);
                                            if (responseData.success == true) {


                                            } else {
                                                Ext.MessageBox.show({
                                                    title: 'Lỗi trong khi thêm nhân viên', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                                });
                                            }
                                        },
                                        failure: function (transport, option) {
                                            var responseData = Ext.decode(transport.responseText);
                                            Ext.MessageBox.show({
                                                title: 'Lỗi trong khi thêm nhân viên', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                            });
                                        }
                                    });

                                    break;
                                }
                            }
                        }
                        
                    } else {
                        var entity = {
                            TaskName: Ext.getCmp('txtTaskName').getValue().trim(),
                            TaskType: Ext.getCmp('radio1').getValue() ? 'S' : 'L',
                            StartDate: Ext.getCmp('txtStartDate').getValue() ? Ext.getCmp('txtStartDate').getValue() : null,
                            EndDate: Ext.getCmp('txtEndDate').getValue() ? Ext.getCmp('txtEndDate').getValue() : null,
                            Descriptions: Ext.getCmp('txtDescript').getValue() ? Ext.getCmp('txtDescript').getValue().trim() : null
                        };

                        Ext.Ajax.request({
                            url: '/api/ApiTask/Create',
                            method: 'POST',
                            jsonData: entity,
                            success: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                if (responseData.success == true) {

                                    var cb = Ext.getCmp('comboboxD2').getValue();

                                    var employees = new Array();
                                    for (var i = 0; i < cb.length; i++) {
                                        var emp = {
                                            EmployeeId: cb[i],
                                            TaskId: responseData.data.TaskId
                                        };
                                        employees[i] = emp;
                                    }

                                    Ext.Ajax.request({
                                        url: '/api/ApiTaskEmployee/CreateList',
                                        method: 'POST',
                                        jsonData: employees,
                                        success: function (transport2, option2) {
                                            var responseData2 = Ext.decode(transport2.responseText);
                                            if (responseData2.success == true) {

                                            } else {
                                                Ext.MessageBox.show({
                                                    title: 'Lỗi trong khi thêm nhân viên', msg: responseData2.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                                });
                                            }
                                        }

                                    });

                                    taskGrid.getStore().insert(0, responseData.data);
                                } else {
                                    Ext.MessageBox.show({
                                        title: 'Lỗi trong khi thêm công việc', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                    });
                                }
                            },
                            failure: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                Ext.MessageBox.show({
                                    title: 'Lỗi', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                });
                            }
                        });
                    }
                }
            }, {
                text: 'Hủy',
                handler: function () {
                    Ext.getCmp('newTaskWindow').close();
                }
            }],
            listeners: {
                afterrender: function (win, eOpts) {
                    var row = win.rec;
                    if (row) {
                        Ext.getCmp('txtTaskName').setValue(row.get('TaskName'));
                        Ext.getCmp('txtStartDate').setValue(row.get('StartDate'));
                        Ext.getCmp('txtEndDate').setValue(row.get('EndDate'));
                        Ext.getCmp('txtDescript').setValue(row.get('Descriptions'));

                        if (row.get('TaskType') == 'S') {
                            Ext.getCmp('radio1').setValue(true);
                        } else {
                            Ext.getCmp('radio2').setValue(true);
                        }
                        
                        Ext.Ajax.request({
                            url: '/api/ApiTaskEmployee/ResourceOfTask',
                            method: 'GET',
                            params: {
                                taskId: row.get('TaskId')
                            },
                            success: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                if (responseData.success == true) {
                                    if (responseData.data) {
                                        var data = [];
                                        for (var i = 0; i < responseData.data.length; i++) {
                                            var cbResult = Ext.create('VTV.TaDMS.Extjs.Model.Combo', {
                                                EmployeeId: responseData.data[i].EmployeeId,
                                                FirstName: responseData.data[i].FirstName,
                                                LastName: responseData.data[i].LastName
                                            });

                                            data.push(cbResult);
                                        }
                                        Ext.getCmp('comboboxD2').setValue(data);
                                    }
                                    
                                    
                                } else {
                                    Ext.MessageBox.show({
                                        title: 'Xảy ra lỗi', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                    });
                                }
                            },
                            failure: function (transport, option) {
                                var responseData = Ext.decode(transport.responseText);
                                Ext.MessageBox.show({
                                    title: 'Lỗi', msg: responseData.message, icon: Ext.MessageBox.ERROR, buttons: Ext.Msg.OK
                                });
                            }
                        });
                    }
                }
            }
        });


    });

</script>
